package com.dimeina.servlet.back;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.dimeina.dao.impl.ProDAOImpl;
import com.dimeina.service.ProService;
import com.dimeina.service.UserService;
import com.dimeina.service.impl.ProServiceImpl;
import com.dimeina.service.impl.UserServiceImpl;
import com.dimeina.vo.ProPicPath;
import com.dimeina.vo.Product;

public class ServletBack extends HttpServlet {

	public ServletBack() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	
	// 全局变量
	ProService proService = new ProServiceImpl();
	ProDAOImpl proDAOImpl = new ProDAOImpl();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		ServletContext application = request.getServletContext();
		String opr = request.getParameter("opr");
		if (opr.equals("delPro")) {
			String id = request.getParameter("id");
			//Product product = proService.findProByID(Integer.parseInt(id));
			
			ProPicPath ppp = proService.findProPicByID(Integer.parseInt(id));
			String realPath = request.getServletContext().getRealPath("upload");
			File file = new File(realPath,ppp.getPicPath1());
			if(file != null && (file.exists() == true)){
			   file.delete();
			}
			
			int result = proService.delProduct(Integer.parseInt(id));
			if (result > 0) {
				response.sendRedirect("/DiMeiNa/admin/proList.jsp");
			}else {
				// 后台打印删除失败
				System.out.println("删除失败！");
			}
		} else if(opr.equals("changePro")){
			String id = request.getParameter("id");
			request.setAttribute("id", id);
			request.getRequestDispatcher("/admin/changeProduct.jsp").forward(request, response);
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String opr = request.getParameter("opr");
		Product product = null;
		ProPicPath ppp = null;
		// 连续判断，是哪个页面传来
		if(opr.equals("user")){
			 request.setCharacterEncoding("utf-8");
		       // 获取账号密码
		       String username = request.getParameter("username");
		       String password = request.getParameter("password");
		       // 用于判断用户登录是否成功
		       boolean judge = false;
		       UserService userServiceImpl = new UserServiceImpl();
		       if(username != null && password != null){
		          if(userServiceImpl.checkUnameUpwd(username, password)){
		             judge = true;
		             // 获取用户登录信息，用以页面之间的传值
		             session.setAttribute("loginName", username);
		             // 过期时间为7天
		             session.setMaxInactiveInterval(3600*24*7);
		          }
		       }
		       
		       // 判断是否登录成功
		       if(judge == true){
		         //创建Cookie对象
		         Cookie usernameCookie = new Cookie("username",username);
		         Cookie passwordCookie = new Cookie("password",password);
		         // 设置Cookie过期时间
		         usernameCookie.setMaxAge(3600*24*7);
		         passwordCookie.setMaxAge(3600*24*7);
		         // 保存Cookie
		         response.addCookie(usernameCookie);
		         response.addCookie(passwordCookie);
		         // 用“请求重定向”调转到“管理员”界面
		         response.sendRedirect("/DiMeiNa/admin/manager.jsp");
		       } else {
		         response.sendRedirect("/DiMeiNa/admin/fail.jsp");
		       }
		}
		else if (opr.equals("addPro")) {
			request.setCharacterEncoding("UTF-8");
			String message = "";
			product = new Product();
			ppp = new ProPicPath();
			
			//服务器保存的上传文件的路径                                                          写文件夹的位置
			String savePath = request.getServletContext().getRealPath("upload");
			// 判断提交的表单中是否是“multipart/form-data”类型属性
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (isMultipart) {
				try {
					// 工厂对象，用于创建ServletFileUpload时传参
					DiskFileItemFactory factory = new DiskFileItemFactory();
					// 创ServletFileUpload对象，用于上传文件
					ServletFileUpload upload = new ServletFileUpload(factory);
					// 将请求对象中的数据转换成为List<FileItem>
					List<FileItem> fileItemList = upload.parseRequest(request);
					for (FileItem item : fileItemList) {
						// true：普通表单数据
						if (item.isFormField() == true) {
							String nameAttrValue = item.getFieldName();
							if (nameAttrValue.equals("topCategoryID")) {
								String topCategoryID = item.getString("UTF-8");
								product.setTopCategoryID(Integer.parseInt(topCategoryID));
							} 
							else if (nameAttrValue.equals("PCategoryID")) {
								String PCategoryID = item.getString("UTF-8");
								product.setPCategoryID(Integer.parseInt(PCategoryID));
							} 
							else if (nameAttrValue.equals("selfCategoryID")) {
								String selfCategoryID = item.getString("UTF-8");
								product.setCategoryID(Integer.parseInt(selfCategoryID));
							} 
							else if (nameAttrValue.equals("proName")) {
								String proName = item.getString("UTF-8");
								product.setName(proName);
							} 
							else if (nameAttrValue.equals("price")) {
								String price = item.getString("UTF-8");
								product.setPrice(Integer.parseInt(price));;
							} 
							else if (nameAttrValue.equals("capacity")) {
								String capacity = item.getString("UTF-8");
								product.setCapacity(Integer.parseInt(capacity));;
							} 
							else if (nameAttrValue.equals("description")) {
								String description = item.getString("UTF-8");
								product.setDescription(description);
							}
							else if (nameAttrValue.equals("ingredient")) {
								String ingredient = item.getString("UTF-8");
								product.setIngredient(ingredient);
							} 
							else if (nameAttrValue.equals("value")) {
								String value = item.getString("UTF-8");
								product.setValue(Integer.parseInt(value));
							} 
							else if (nameAttrValue.equals("inventory")) {
								String inventory = item.getString("UTF-8");
								product.setInventory(Integer.parseInt(inventory));;
							} 
							else if (nameAttrValue.equals("content")) {
								String content = item.getString("UTF-8");
								product.setContent(content);
							}
						}
						// false 文件域
						else {
							// 文件上传
							// 获得客户端上传文件的完整路径
							String uploadFilePath = item.getName();
							if (uploadFilePath != null && !uploadFilePath.equals("")) {
								// ★★★ 用完整路径作为参数，创建File对象，此对象会包含很多数据
								File fullFile = new File(uploadFilePath);
								// 从“全路径”里面抽取“文件名”  解决IE 兼容问题
								String fileName = fullFile.getName();
								// 用“服务器”的“保存路径”和“文件名” 创File对象
								// 通过write()将对象保存到服务器指定路径
								item.write(new File(savePath, fileName));
								String picpath = fullFile.getName();
								ppp.setPicPath1(picpath);
							}
						}
					}
				} catch (Exception ex) {
					message = "上传文件失败，失败原因是" + ex.getMessage();
				}
				// 通过业务处理 将Product 和 ProPicPath 同时上传
				// 将Product的id主键 赋予 ProPicPath的id主键，以同时插入
				int mainKey = proService.addPro(product);
				ppp.setId(mainKey);
				int result = proService.addProPic(ppp);
				if (result > 0) {
					response.sendRedirect("/DiMeiNa/admin/proList.jsp");
				} else {
					message = "发布商品失败！";
					request.setAttribute("message", message);
					request.getRequestDispatcher("/admin/addProduct.jsp").forward(request, response);
				}
			}
		} else if(opr.equals("changePro")){
			String id = request.getParameter("id");
			request.setCharacterEncoding("UTF-8");
			String message = "";
			product = new Product();
			ppp = new ProPicPath();
			
			//服务器保存的上传文件的路径                                                          写文件夹的位置
			String savePath = request.getServletContext().getRealPath("upload");
			// 判断提交的表单中是否是“multipart/form-data”类型属性
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (isMultipart) {
				try {
					// 工厂对象，用于创建ServletFileUpload时传参
					DiskFileItemFactory factory = new DiskFileItemFactory();
					// 创ServletFileUpload对象，用于上传文件
					ServletFileUpload upload = new ServletFileUpload(factory);
					// 将请求对象中的数据转换成为List<FileItem>
					List<FileItem> fileItemList = upload.parseRequest(request);
					for (FileItem item : fileItemList) {
						// true：普通表单数据
						if (item.isFormField() == true) {
							String nameAttrValue = item.getFieldName();
							if (nameAttrValue.equals("topCategoryID")) {
								String topCategoryID = item.getString("UTF-8");
								product.setTopCategoryID(Integer.parseInt(topCategoryID));
							} 
							else if (nameAttrValue.equals("PCategoryID")) {
								String PCategoryID = item.getString("UTF-8");
								product.setPCategoryID(Integer.parseInt(PCategoryID));
							} 
							else if (nameAttrValue.equals("selfCategoryID")) {
								String selfCategoryID = item.getString("UTF-8");
								product.setCategoryID(Integer.parseInt(selfCategoryID));
							} 
							else if (nameAttrValue.equals("proName")) {
								String proName = item.getString("UTF-8");
								product.setName(proName);
							} 
							else if (nameAttrValue.equals("price")) {
								String price = item.getString("UTF-8");
								product.setPrice(Integer.parseInt(price));;
							} 
							else if (nameAttrValue.equals("capacity")) {
								String capacity = item.getString("UTF-8");
								product.setCapacity(Integer.parseInt(capacity));;
							} 
							else if (nameAttrValue.equals("description")) {
								String description = item.getString("UTF-8");
								product.setDescription(description);
							}
							else if (nameAttrValue.equals("ingredient")) {
								String ingredient = item.getString("UTF-8");
								product.setIngredient(ingredient);
							} 
							else if (nameAttrValue.equals("value")) {
								String value = item.getString("UTF-8");
								product.setValue(Integer.parseInt(value));
							} 
							else if (nameAttrValue.equals("inventory")) {
								String inventory = item.getString("UTF-8");
								product.setInventory(Integer.parseInt(inventory));;
							} 
							else if (nameAttrValue.equals("content")) {
								String content = item.getString("UTF-8");
								product.setContent(content);
							}
						}
						// false 文件域
						else {
							// 文件上传
							// 获得客户端上传文件的完整路径
							String uploadFilePath = item.getName();
							if (uploadFilePath != null && !uploadFilePath.equals("")) {
								// ★★★ 用完整路径作为参数，创建File对象，此对象会包含很多数据
								File fullFile = new File(uploadFilePath);
								// 从“全路径”里面抽取“文件名”  解决IE 兼容问题
								String fileName = fullFile.getName();
								// 用“服务器”的“保存路径”和“文件名” 创File对象
								// 通过write()将对象保存到服务器指定路径
								item.write(new File(savePath, fileName));
								String picpath = fullFile.getName();
								ppp.setPicPath1(picpath);
							}
						}
					}
				} catch (Exception ex) {
					message = "上传文件失败，失败原因是" + ex.getMessage();
				}
				// 通过业务处理 将Product 和 ProPicPath 同时上传
				// 将Product的id主键 赋予 ProPicPath的id主键，以同时插入
				// 执行详情插入
				product.setId(Integer.parseInt(id));
				proDAOImpl.updPro(product);
				// 执行图片插入
				ppp.setId(Integer.parseInt(id));
				int result = proService.updProPic(ppp);
				if (result > 0) {
					response.sendRedirect("/DiMeiNa/admin/proList.jsp");
				} else {
					message = "修改商品失败！";
					request.setAttribute("message", message);
					request.getRequestDispatcher("/admin/changeProduct.jsp").forward(request, response);
				}
			}
		}

	}

	public void init() throws ServletException {
		// Put your code here
	}

}
